import axios from 'axios';
import { mockPointsRecords, mockSubmitContribution } from './mock/points';

// 判断是否使用mock数据
const isMock = process.env.NODE_ENV === 'development';

/**
 * 提交数据贡献
 * @param {Object} data - 贡献数据
 * @param {string} data.code - 贡献码
 * @param {string} data.hash - 贡献hash
 * @returns {Promise<Object>} - 返回结果
 */
export const submitContribution = async (data) => {
  if (isMock) {
    return mockSubmitContribution(data);
  }
  
  try {
    const response = await axios.post('/api/points/contribution/submit', data);
    return response.data;
  } catch (error) {
    console.error('提交数据贡献失败:', error);
    return {
      code: -1,
      message: '提交失败，请稍后重试'
    };
  }
};

/**
 * 获取最近贡献记录
 * @returns {Promise<Object>} - 返回结果
 */
export const getRecentContributions = async () => {
  if (isMock) {
    return {
      code: 0,
      data: mockPointsRecords.filter(record => record.type === '数据贡献').slice(0, 3)
    };
  }
  
  try {
    const response = await axios.get('/api/points/contribution/recent');
    return response.data;
  } catch (error) {
    console.error('获取最近贡献记录失败:', error);
    return {
      code: -1,
      message: '获取记录失败，请稍后重试'
    };
  }
};

/**
 * 获取积分记录
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页条数
 * @param {string} [params.type] - 记录类型
 * @returns {Promise<Object>} - 返回结果
 */
export const getPointsRecords = async (params) => {
  if (isMock) {
    // 模拟分页和筛选
    let records = [...mockPointsRecords];
    
    // 根据类型筛选
    if (params.type) {
      if (params.type === 'income') {
        records = records.filter(record => record.isIncome);
      } else if (params.type === 'expense') {
        records = records.filter(record => !record.isIncome);
      } else if (params.type === 'contribution') {
        records = records.filter(record => record.type === '数据贡献');
      }
    }
    
    // 计算总数
    const total = records.length;
    
    // 分页
    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;
    records = records.slice(start, end);
    
    return {
      code: 0,
      data: {
        list: records,
        total: total,
        page: params.page,
        pageSize: params.pageSize
      }
    };
  }
  
  try {
    const response = await axios.get('/points/records', { params });
    return response.data;
  } catch (error) {
    console.error('获取积分记录失败:', error);
    return {
      code: -1,
      message: '获取记录失败，请稍后重试'
    };
  }
};